'use client';

import React, { useEffect, useState } from 'react';
import {
  Button, Descriptions, Form, Input, message, Modal, Select, Space,
} from 'antd';
import { getClusters, getNameSpace, createDeploy } from '../../api/deploy';

function App({ refreshData }) {
  const [clusters, setClusters] = useState([]);
  const [namespace, setNamespace] = useState([]);
  const [selectCluster, setSelectCluster] = useState('');

  const [form] = Form.useForm();
  const [formValues, setFormValues] = useState();
  const [open, setOpen] = useState(false);
  const onCreate = (values) => {
    console.log('Received values of form: ', values);
    const params = {
      alias: values.alias,
      cluster: {
        clusterName: values.clusterName,
        namespace: values.namespace,
      },
      description: values.description,
      name: values.name,
      project: 'default',
      variable: { providerName: '' },
    };
    setFormValues(values);
    createDeploy(params).then((res) => {
      if (res) {
        message.success('新增资源成功！');
        refreshData();
        setOpen(false);
      }
    });
  };
  const handleChange = (value) => {
    console.log(`selected ${value}`);
  };
  const handleChangeClusters = (value) => {
    setSelectCluster(value);
    console.log(`selected ${value}`);
  };
  useEffect(() => {
    getClusters().then((res) => {
      if (res) {
        setClusters(res.clusters);
      }
      console.log('getClusters', res);
    });
  }, []);
  useEffect(() => {
    if (selectCluster && selectCluster !== '') {
      getNameSpace(selectCluster).then((res) => {
        const resData = [];
        if (res) {
          for (let i = 0; i < res.list.length; i += 1) {
            if (res.list[i].metadata.labels['usage.oam.dev/runtime'] === undefined || res.list[i].metadata.labels['usage.oam.dev/runtime'] === ''
            ) {
              resData.push({ name: res.list[i].metadata.name, value: res.list[i].metadata.name });
            }
          }
        }
        setNamespace(resData);
        console.log('getNameSpace', resData);
      });
    }
  }, [selectCluster]);
  return (
    <>
      <Button type="primary" onClick={() => setOpen(true)}>
        新增资源
      </Button>
      <Modal
        open={open}
        title="新增资源"
        okText="确认"
        cancelText="取消"
        okButtonProps={{
          autoFocus: true,
          htmlType: 'submit',
        }}
        onCancel={() => setOpen(false)}
        destroyOnClose
        modalRender={(dom) => (
          <Form
            layout="vertical"
            form={form}
            name="form_in_modal"
            initialValues={{
              modifier: 'public',
            }}
            labelCol={{
              span: 8,
            }}
            wrapperCol={{
              span: 16,
            }}
            style={{
              width: '100%',
              maxWidth: 600,
            }}
            clearOnDestroy
            onFinish={(values) => onCreate(values)}
          >
            {dom}
          </Form>
        )}
      >
        <Form.Item
          name="name"
          label="标识"
          style={{ display: 'inline-block', width: '200px' }}
          rules={[
            {
              required: true,
              message: '请输入标识!',
            },
          ]}
        >
          <Input
            placeholder="请输入标识!"
            style={{ width: '180px' }}
          />
        </Form.Item>
        <Form.Item
          name="alias"
          label="名称"
          style={{ display: 'inline-block', width: '200px' }}

          rules={[
            {
              required: true,
              message: '请输入名称!',
            },
          ]}
        >
          <Input
            placeholder="请输入名称!"
            style={{ width: '180px' }}
          />
        </Form.Item>
        <Form.Item name="description" label="描述">
          <Input type="textarea" placeholder="请输入描述!" style={{ width: '380px' }} />
        </Form.Item>
        <Form.Item
          name="cluster"
          style={{
            marginBottom: 0,
          }}
        >
          <Space>
            <Form.Item
              name="clusterName"
              label="集群"
              rules={[
                {
                  required: true,
                  message: '请选择集群!',
                },
              ]}
              style={{
                display: 'inline-block',
                width: '150px',
              }}
            >
              <Select
                style={{
                  width: 120,
                }}
                onChange={handleChangeClusters}
                notFoundContent="数据为空"
                options={clusters}
                fieldNames={{ label: 'name', value: 'name' }}
                placeholder="请选择.."
              />
            </Form.Item>
            <Form.Item
              name="namespace"
              label="命名空间"
              rules={[
                {
                  required: true,
                  message: '请选择命名空间!',
                },
              ]}
              style={{
                display: 'inline-block',
                width: '150px',
              }}
            >
              <Select
                style={{
                  width: 120,
                }}
                notFoundContent="数据为空"
                onChange={handleChange}
                options={namespace}
                placeholder="请选择.."
              />
            </Form.Item>
            <Button>新增</Button>
          </Space>
        </Form.Item>
      </Modal>
    </>
  );
}
export default App;
